//
//  NetworkTools.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/7.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
import Alamofire

class NetworkTools {
  private let AppKey = "836544493"
  private let AppSecret = "5559490a0898c5207328d255cf86d587"
  private let redirectUrl = "http://www.baidu.com"
    private var tokenDict: [String: AnyObject]?{
        if let token = UserAccountVM.shareUserAccount.accessToken{
            return ["access_token": token]
        }
        return nil
    }
    static let onceToken = NetworkTools()
    typealias JLRequestCallBack = (result: AnyObject? , error: NSError?)->()

    func request(method: Alamofire.Method,URLString: String, parameters: [String: AnyObject]?, finished: (result: AnyObject?,error :NSError?) -> Void){
      Alamofire.request(method, URLString, parameters: parameters).responseJSON { (response) -> Void in
        if response.result.isFailure {
            print("发送网络请求错误")
        }
        finished(result: response.result.value, error: response.result.error)
        }
        
    }
    func sendStatus(status: String,image: UIImage?,success: JLRequestCallBack){
        var parameters = [String : AnyObject]()
        parameters["status"] = status
        if image == nil{
            
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            tokenRequest(.POST, success: success, urlString: urlString, parameters: parameters)
        }else{
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
              let data = UIImagePNGRepresentation(image!)
            uploadStatus(urlString, name: "pic", parameters: parameters, success: success, data: data!)
        }
    }
 
    }
extension NetworkTools{

    func loadStatus(since_id since_id: Int, max_id:Int,success:JLRequestCallBack){
        guard var param = tokenDict else{
            success(result: nil, error: NSError(domain: "con.itcast.hm", code: -1002, userInfo: ["message":"tokenDict为空"]))
            return
        }
        if since_id>0{
            param["since_id"] = since_id
        }else if max_id > 0{
            param["max_id"] = max_id-1
        }
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
       request(Alamofire.Method.GET, URLString: urlString, parameters: param, finished: success)
    
        
    }
    private func appendToken(inout parameters: [String:AnyObject]?)-> Bool{
        guard let token = UserAccountVM.shareUserAccount.accessToken else{
            return false
        }
        if parameters == nil {
            parameters = [String : AnyObject]()
        }
        parameters!["access_token"] = token
        return true
    }
    private func tokenRequest(method: Alamofire.Method, success: JLRequestCallBack, urlString: String, var parameters: [String:AnyObject]?){
        if !appendToken(&parameters){
            success(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["messsage":"token为空"]))
            return
        }
        request(method, URLString:urlString , parameters: parameters, finished: success)
    }
    /// 发送网络请求,加载用户数据
    ///
    /// - parameter access_token: access_token
    /// - parameter uid:          uid
    /// - parameter sucess:       加载完后闭包回调
    /// -see :[http://open.weibo.com/wiki/Oauth2/authorize] (https://api.weibo.com/2/users/show.json )
    func loadUserinfo( uid: String ,sucess: JLRequestCallBack ){
       
        let urlString = "https://api.weibo.com/2/users/show.json"
        var params = [String : AnyObject]()
        params["uid"] = uid
       tokenRequest(.GET, success: sucess, urlString: urlString, parameters: params)
    }
    func loadAccessToken(code: String,finished: (result: AnyObject?,error :NSError?) -> Void) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        request(Alamofire.Method.POST, URLString: urlString, parameters: params, finished: finished)
        
    }
    var oauthURl: NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redirectUrl)"
        return NSURL(string: urlString)!
    }
    ///上传微博
    private func uploadStatus(urlString: String , name: String , var parameters: [String: AnyObject]? ,success: JLRequestCallBack,data: NSData){
        if !appendToken(&parameters){
            success(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["messsage":"token为空"]))
            return

        }
        
//        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (framData) -> Void in
//            framData.appendPartWithFileData(data, name: name, fileName: "123123", mimeType: "application/octet-stream")
//            }, success: { (result, _) -> Void in
//                success(result: result, error: nil)
//            }) { (_, error) -> Void in
//                success(result: nil, error: error)
//
//        }
        
    }
    
}
